package com.fx.zmlzml.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring 应用上下文持有类
 * 用于在非Spring管理的类中获取Spring的ApplicationContext
 */
@Component
public class ApplicationContextHolder implements ApplicationContextAware {

    /**
     * 保存Spring应用上下文的静态实例
     */
    private static ApplicationContext applicationContext;

    /**
     * 获取ApplicationContext实例
     * @return ApplicationContext实例
     */
    public static ApplicationContext getApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("ApplicationContextHolder not initialized yet");
        }
        return applicationContext;
    }

    /**
     * 根据类型获取Spring管理的Bean
     * @param clazz Bean的类型
     * @param <T> Bean的泛型类型
     * @return Bean实例
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 根据名称和类型获取Spring管理的Bean
     * @param name Bean的名称
     * @param clazz Bean的类型
     * @param <T> Bean的泛型类型
     * @return Bean实例
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

    /**
     * 设置ApplicationContext（由Spring框架调用）
     * @param applicationContext Spring应用上下文
     * @throws BeansException 设置上下文时可能抛出的异常
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHolder.applicationContext = applicationContext;
    }
}